<template>
  <div>
    <el-form style=" align-items: center; gap: 16px; margin-bottom: 20px;">
    <el-input v-model="filters.clientName" placeholder="客户姓名" class="filter-input" @input="handleFiltersChange" style="margin-left: 16px; width: 150px;"></el-input>
    </el-form>


    <!--  客户信息列表  -->
    <el-table :data="arr" stripe border :row-key="'clientId'" >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="clientName" label="客户姓名" width = "120"></el-table-column>
      <el-table-column prop="clientGender" label="性别"></el-table-column>
      <el-table-column prop="clientAge" label="年龄" ></el-table-column>
      <el-table-column prop="dateOfBirth" label="出生日期" width = "160"></el-table-column>
      <el-table-column prop="bloodType" label="血型" ></el-table-column>
      <el-table-column prop="familyMember" label="家属" ></el-table-column>
      <el-table-column prop="clientPhone" label="电话号码" width = "160"></el-table-column>
      <el-table-column prop="careLevelName" label="护理级别" width = "140"></el-table-column>
      <el-table-column label="护理级别" width = "160">
        <template #default="{ row, rowIndex }">
          <el-button size="small" type="danger" @click="removeCareLevel(row.clientId)">移除</el-button>
          <el-button size="small" type="primary" @click="setCareLevel((row))">设置</el-button>
        </template>
      </el-table-column>
      <el-table-column label="护理项目" width = "160">
        <template #default="{ row, rowIndex }">
          <el-button size="small" type="success" @click="seeClientCareItem(row)">查看</el-button>
          <el-button size="small" type="primary" @click="showAddCareItemDialog(row)">添加</el-button>
        </template>
      </el-table-column>
      <el-table-column label="护理记录" width = "140">
        <template #default="{ row, rowIndex }">
          <el-button size="small" type="success" @click="seeCareRecord(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 客户列表分页 -->
    <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: left;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="clientPagination.total"
          v-model:current-page="clientPagination.current"
          v-model:page-size="clientPagination.size"
          :page-sizes="[1, 10, 20, 50]"
          @current-change="handleClientPageChange"
          @size-change="handleClientSizeChange"
      />
    </div>


    <!-- 查看客户护理记录对话框 -->
    <el-dialog title="客户护理记录" v-model="seeCareRecordDialogVisible" width="50%">
      <el-form style="align-items: center; gap: 16px; margin-bottom: 20px; display: inline-flex; align-items: center;">
        <!-- 输入框 -->
        <el-input
            v-model="filterCareItemName"
            placeholder="请输入护理项目名称"
            clearable
            style="width: 300px; margin-left: 16px; margin-bottom: 0; height: 40px;"
        ></el-input>

        <!-- 查询按钮 -->
        <el-button
            type="primary"
            @click="seeCareRecord"
            style="height: 40px; margin-bottom: 0;"
        >查询</el-button>
      </el-form>
      <el-table
          :data="clientCareRecords"
          stripe border
          highlight-current-row
          style="align-items: center; gap: 16px; width: 100%; margin-bottom: 20px;"
          max-height="400px"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="careItemName" label="护理项目" width="120"/>
        <el-table-column prop="careTime" label="护理时间" width="200"/>
        <el-table-column prop="careCount" label="护理数量" width="100"/>
        <el-table-column prop="careContent" label="护理内容"/>
        <el-table-column prop="adName" label="护理人员" width="100"/>
        <el-table-column label="操作" width = "80">
          <template #default="{ row, rowIndex }">
            <el-button size="small" type="danger" @click="removeCareRecord(row,row.careRecordId)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>



    <!-- 添加客户护理项目对话框 -->
    <el-dialog title="添加客户护理项目" v-model="addCareItemDialogVisible" width="50%">
      <el-form :model="addCareItemDialogData" label-width="120px">
<!--        <el-table :data="addClientCareItems" highlight-current-row @selection-change="handleSelectionChange">-->
<!--          <el-table-column type="selection" width="55" />-->
<!--          <el-table-column prop="careItemCode" label="项目编号" />-->
<!--          <el-table-column prop="careItemName" label="项目名称" />-->
<!--          <el-table-column prop="careItemCycle" label="执行周期" />-->
<!--          <el-table-column prop="careItemCount" label="执行次数" />-->
<!--        </el-table>-->
        <el-table
            :data="addClientCareItems"
            stripe border
            highlight-current-row
            @selection-change="handleSelectionChange"
            style="align-items: center; gap: 16px; width: 100%; margin-bottom: 20px;"
            max-height="400px"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="careItemCode" label="项目编号" />
        <el-table-column prop="careItemName" label="项目名称"/>
        <el-table-column prop="careItemCycle" label="执行周期"/>
        <el-table-column prop="careItemCount" label="执行次数" width="100"/>
        </el-table>
<!--        &lt;!&ndash; 护理项目列表分页 &ndash;&gt;-->
<!--        <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: right;">-->
<!--          <el-pagination-->
<!--              background-->
<!--              layout="total, sizes, prev, pager, next, jumper"-->
<!--              :total="levelItemPagination.total"-->
<!--              v-model:current-page="levelItemPagination.current"-->
<!--              v-model:page-size="levelItemPagination.size"-->
<!--              :page-sizes="[1, 10, 20, 50]"-->
<!--              @current-change="handleLevelItemPageChange"-->
<!--              @size-change="handleLevelItemSizeChange"-->
<!--          />-->
<!--        </div>-->
        <el-form-item label="购买服务日期">
          <el-input v-model="addCareItemDialogData.servicePurchaseDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input v-model="addCareItemDialogData.serviceCount"></el-input>
        </el-form-item>
        <el-form-item label="服务到期日期">
          <el-date-picker
              v-model="addCareItemDialogData.serviceEndDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务状态">
          <el-input v-model="addCareItemDialogData.serviceStatus"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCareItemDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddCareItems">确 定</el-button>
      </div>
    </el-dialog>



<!--    &lt;!&ndash; 设置护理级别对话框 &ndash;&gt;-->
<!--    <el-dialog title="设置级别" v-model="setCareLevelDialogVisible" width="30%">-->
<!--      <el-form :model="setCareLevelDialogData" label-width="80px">-->
<!--        <el-form-item label="级别名称">-->
<!--          <el-input v-model="setCareLevelDialogData.careLevelId"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-button @click="setCareLevelDialogVisible = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="submitSetCareLevel">确 定</el-button>-->
<!--      </el-form>-->
<!--    </el-dialog>-->
    <el-dialog title="设置级别" v-model="setCareLevelDialogVisible" width="30%">
      <el-form :model="setCareLevelDialogData" label-width="80px">
        <el-form-item label="护理级别">
          <!-- 下拉框选择护理级别 -->
          <el-select v-model="setCareLevelDialogData.careLevelId" placeholder="请选择护理级别">
            <!-- 循环遍历careLevels来生成每个选项 -->
            <el-option
                v-for="level in careLevels"
                :key="level.careLevelId"
                :label="level.careLevelName"
                :value="level.careLevelId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setCareLevelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetCareLevel">确 定</el-button>
      </div>
    </el-dialog>



    <!-- 查看客户护理项目对话框 -->
    <el-dialog title="客户护理项目" v-model="seeClientCareItemDialogVisible" width="50%">
      <el-table :data="clientCareItems" stripe border highlight-current-row max-height="400px">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="servicePurchaseDate" label="购买服务日期" width="120"/>
        <el-table-column prop="serviceCount" label="护理数量" />
        <el-table-column prop="serviceEndDate" label="服务到期日期" width="120"/>
        <el-table-column prop="careItemName" label="护理项目" />
        <el-table-column prop="careLevelName" label="护理级别" />
        <el-table-column prop="serviceStatus" label="服务项目状态" width="120"/>
        <el-table-column label="操作" width = "135">
          <template #default="{ row, rowIndex }">
            <el-button size="small" type="primary" @click="showRenewDialog(row)">续费</el-button>
            <el-button size="small" type="danger" @click="removeClientCareItem(row,row.clientCareItemId)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>



    <!-- 续费对话框 -->
    <el-dialog title="续费护理项目" v-model="renewDialogVisible" width="40%">
      <el-form :model="renewDialogData" label-width="120px">
        <el-form-item label="客户护理项目">
          <el-input v-model="renewDialogData.clientCareItem" disabled></el-input>
        </el-form-item>
        <el-form-item label="原有数量">
          <el-input v-model="renewDialogData.originalCount" disabled></el-input>
        </el-form-item>
        <el-form-item label="新增数量">
          <el-input v-model="renewDialogData.newCount"></el-input>
        </el-form-item>
        <el-form-item label="总数量">
          <el-input v-model="renewDialogData.totalCount" disabled></el-input>
        </el-form-item>
        <el-form-item label="服务到期日期">
          <el-date-picker
              v-model="renewDialogData.serviceEndDate"
              type="date"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRenew">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, inject, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'



// 移除客户护理项目
async function removeClientCareItem(row,clientCareItemId) {
  try {
    // 确认是否移除
    await ElMessageBox.confirm('确认移除该客户护理项目？', '提示', { type: 'warning' });
    // 发送请求到后端
    const url = `ClientCareItemController/deleteCareItem?clientCareItemId=${clientCareItemId}`;
    const responseData = await axios.post(url);
    // 检查返回的数据
    if (responseData) {
      // 移除成功
      ElMessage.success('移除成功');
      // 重新获取客户护理项目列表
      seeClientCareItem(row);
    } else {
      // 移除失败
      ElMessage.error('移除失败：未返回有效数据');
    }
  } catch (error) {
    // 捕获错误
    console.error('移除客户护理项目时发生错误：', error);
    ElMessage.error('移除失败：' + (error.message || '未知错误'));
  }
  init();
}



// 客户护理记录列表
// 筛选护理项目
const filterCareItemName = ref();
const clientCareRecords = ref([]);
const clientId = ref();
const seeCareRecordDialogVisible = ref(false)
// 点击护理记录栏“查看”按钮所触发的事件
async function seeCareRecord(row) {
  try {
    console.log(row);
    if(row.clientId != null){
      clientId.value = row.clientId;
      console.log(clientId);

    }
    // 获取护理记录列表
    const url = 'CareRecordController/getCareRecordByClientId';
    clientCareRecords.value = await axios.get(url, {
      params: {
        clientId: clientId.value,
        careItemName: filterCareItemName.value
      }
    });
    // 格式化护理时间
    const formattedRecords = clientCareRecords.value.map(record => {
      const date = new Date(record.careTime); // 假设护理时间字段名为 careTime
      const formattedDate = formatDate(date);
      return { ...record, careTime: formattedDate };
    });
    // 显示护理记录对话框
    clientCareRecords.value = formattedRecords;
    // 显示护理记录对话框
    seeCareRecordDialogVisible.value = true;
  } catch (error) {
    console.error('获取客户护理记录失败：', error);
    ElMessage.error('获取客户护理记录失败：' + (error.message || '未知错误'));
    seeCareRecordDialogVisible.value = true;
    clientCareRecords.value=[];
  }
}
// 数据库时间转换
function formatDate(date) {
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  let hours = date.getHours().toString().padStart(2, '0');
  let minutes = date.getMinutes().toString().padStart(2, '0');
  let seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}




// 移除客户护理记录
async function removeCareRecord(row,careRecordId) {
  try {
    // 确认是否移除
    await ElMessageBox.confirm('确认移除该客户护理记录？', '提示', { type: 'warning' });
    // 发送请求到后端
    const url = `CareRecordController/deleteCareRecord?careRecordId=${careRecordId}`;
    const responseData = await axios.post(url);
    // 检查返回的数据
    if (responseData) {
      // 移除成功
      ElMessage.success('移除成功');
      // 重新获取护理记录列表
      seeCareRecord(row);
    } else {
      // 移除失败
      ElMessage.error('移除失败：未返回有效数据');
    }
  } catch (error) {
    // 捕获错误
    console.error('移除护理记录时发生错误：', error);
    ElMessage.error('移除失败：' + (error.message || '未知错误'));
  }
  init();
}


// 续费客户护理项目
const renewDialogVisible = ref(false)
const renewDialogData = reactive({
  clientCareItemId: 0,
  clientCareItem: "",
  originalCount: 0,
  newCount: 0,
  totalCount: 0,
  serviceEndDate: ''
})
// 显示续费对话框
function showRenewDialog(row) {
  renewDialogData.clientCareItemId = row.clientCareItemId
  renewDialogData.clientCareItem = row.careItemName
  renewDialogData.originalCount = row.serviceCount
  renewDialogData.newCount = 0
  renewDialogData.totalCount = computed(() => Number(renewDialogData.originalCount) + Number(renewDialogData.newCount));
  renewDialogData.serviceEndDate = new Date(new Date().setMonth(new Date().getMonth() + 3))
  // renewDialogData.serviceEndDate = row.serviceEndDate || new Date(new Date().setMonth(new Date().getMonth() + 3))
  renewDialogVisible.value = true
}
// 提交续费请求
async function submitRenew() {
  try {
    const response = await axios.post('ClientCareItemController/updateClientCareItem', {
      clientCareItemId: renewDialogData.clientCareItemId,
      serviceCount: renewDialogData.totalCount,
      serviceEndDate: renewDialogData.serviceEndDate
    })
    if (response) {
      ElMessage.success('续费成功')
      renewDialogVisible.value = false
      // 重新获取护理项目列表(客户护理项目列表显示更新（续费）后的客户护理项目)
      seeClientCareItem(clientCareItems.value.find(item => item.clientCareItemId === renewDialogData.clientCareItemId));
    } else {
      ElMessage.error('续费失败：未返回有效数据')
    }
  } catch (error) {
    console.error('续费失败：', error)
    ElMessage.error('续费失败：' + (error.message || '未知错误'))
  }
  init();
}


// 级别项目列表分页功能
const levelItemPagination = reactive({ current: 1, size: 10, total: 0 })
function handleLevelItemPageChange(p) {
  levelItemPagination.current = p; fetchCareItems(selectedCareLevelId.value)
}
function handleLevelItemSizeChange(s) {
  console.log(selectedCareLevelId)
  levelItemPagination.size = s; levelItemPagination.current = 1; fetchCareItems(selectedCareLevelId.value)
}



// 添加客户护理项目
const addCareItemDialogVisible = ref(false)   // 添加对话框是否显示
const addCareItemDialogData = reactive({
  servicePurchaseDate: new Date().toISOString().split('T')[0], // 默认购买日期为当天
  serviceCount: 1, // 默认购买数量为1
  serviceEndDate: new Date(new Date().setMonth(new Date().getMonth() + 3)), // 服务到期日期
  serviceStatus: '正常', // 默认服务状态为启用
  selectedCareItems: [] // 选中的护理项目
});
// 选中的护理项目列表
const selectedCareItems = ref([]);
const addClientCareItems = ref([]);
const selectedCareLevelId = ref(null);
const selectedClientId = ref(null);
// 获取当前护理级别下的所有启用护理项目
async function fetchCareItems(careLevelId) {
  console.log(careLevelId);
  try {
    let url = `LevelItemController/levelItemNoPage`
    let params = {
      careLevelId: careLevelId,
      // page: levelItemPagination.current,
      // size: levelItemPagination.size
    };
    addClientCareItems.value = await axios.get(url, {
      params: params
    });
    // addClientCareItems.value = data.records
    // levelItemPagination.total = data.total
  } catch (error) {
    console.error('获取护理项目失败：', error);
    ElMessage.error('获取护理项目失败：' + (error.message || '未知错误'));
  }
}
// 显示添加客户护理项目对话框
function showAddCareItemDialog(row) {
  selectedClientId.value = row.clientId;
  selectedCareLevelId.value = row.careLevelId;
  console.log(row.careLevelId);
  console.log(selectedCareLevelId);
  fetchCareItems(selectedCareLevelId.value);
  addCareItemDialogVisible.value = true;
}
// 提交添加客户护理项目请求
async function submitAddCareItems() {
  try {
    const requestData = selectedCareItems.value.map(item => ({
      careItemId: item.careItemId,
      clientId: selectedClientId.value,
      careLevelId: selectedCareLevelId.value,
      serviceStatus: addCareItemDialogData.serviceStatus,
      serviceEndDate: addCareItemDialogData.serviceEndDate,
      serviceCount: addCareItemDialogData.serviceCount,
      servicePurchaseDate: addCareItemDialogData.servicePurchaseDate
    }));
    const response = await axios.post('ClientCareItemController/batchInsertClientCareItems', requestData);
    if (response) {
      ElMessage.success('添加成功');
      addCareItemDialogVisible.value = false;
      // 重新获取客户护理项目列表
      // seeClientCareItem(clientCareItems.value.find(item => item.clientCareItemId === addCareItemDialogData.clientId));
    } else {
      ElMessage.error('添加失败：未返回有效数据');
    }
  } catch (error) {
    console.error('添加失败：', error);
    ElMessage.error('添加失败：' + (error.message || '未知错误'));
  }
}
// 处理护理项目选择变化的事件
function handleSelectionChange(selection) {
  selectedCareItems.value = selection;
}




// 设置客户护理级别
const setCareLevelDialogVisible = ref(false)
// 用于保存所有护理级别
const careLevels = ref([]);
const setCareLevelDialogData = reactive({
  careLevelId: null,
  clientId: 0
});
// 获取护理级别列表
const fetchCareLevels = async () => {
  try {
    const response = await axios.get('CareLevelController/listCareLevelByStatusNP', {
      params: {
        careLevelStatus: true, // 获取启用的护理级别
      }
    });
    careLevels.value = response; // 假设返回的数据结构为 { careLevelId, careLevelName }
  } catch (error) {
    ElMessage.error('获取护理级别失败：' + (error.message || '未知错误'));
  }
};
// 设置护理级别按钮事件
async function setCareLevel(row) {
  // 检查当前行的护理级别是否为空
  if (row.careLevelId === null || row.careLevelId === undefined) {
    // 如果为空，将当前行的数据复制到表单数据中，并打开对话框
    setCareLevelDialogData.clientId = row.clientId;
    setCareLevelDialogData.careLevelId = null;
    setCareLevelDialogVisible.value = true;
  } else {
    // 如果不为空，提示用户已有护理级别，无法设置
    ElMessage.warning('该客户已有护理级别，无法设置。如需修改，请先移除再设置。');
  }
}
async function submitSetCareLevel() {
  if (!setCareLevelDialogData.careLevelId) {
    ElMessage.error('请选择护理级别');
    return;
  }
  try {
    console.log(setCareLevelDialogData.clientId);
    const response = await axios.post('client/setCareLevelId', null, {
      params: {
        clientId: setCareLevelDialogData.clientId,
        careLevelId: setCareLevelDialogData.careLevelId
      }
    });
    if (response) {
      ElMessage.success('设置成功');
      setCareLevelDialogVisible.value = false;
    } else {
      ElMessage.error('设置失败：未返回有效数据');
    }
  } catch (error) {
    console.error('设置失败：', error);
    ElMessage.error('设置失败：' + (error.message || '未知错误'));
  }
  init();
}




// 查看客户护理项目
const seeClientCareItemDialogVisible = ref(false)
// 激活的护理项目列表
const clientCareItems = ref([]);
// 点击护理项目栏“查看”按钮所触发的事件
async function seeClientCareItem(row) {
  try {
    // 获取激活的护理项目列表
    const url = 'ClientCareItemController/getClientCareItemsByClientId';
    clientCareItems.value = await axios.get(url, {
      params: {
        clientId: row.clientId
      }
    });
    // 显示护理项目配置对话框
    seeClientCareItemDialogVisible.value = true;
  } catch (error) {
    // console.error('获取客户护理项目失败：', error);
    // ElMessage.error('获取客户护理项目失败：' + (error.message || '未知错误'));
    seeClientCareItemDialogVisible.value = true;
    clientCareItems.value=[];
  }
}



// 移除客户护理级别
async function removeCareLevel(clientId) {
  try {
    // 确认是否移除
    await ElMessageBox.confirm('确认移除该客户护理级别？', '提示', { type: 'warning' });

    // 发送请求到后端
    const url = `client/deleteCareLevelId?clientId=${clientId}`;
    const responseData = await axios.post(url);

    // 检查返回的数据
    if (responseData) {
      // 移除成功
      ElMessage.success('移除成功');
    } else {
      // 移除失败
      ElMessage.error('移除失败：未返回有效数据');
    }
  } catch (error) {
    // 捕获错误
    console.error('移除护理级别时发生错误：', error);
    ElMessage.error('移除失败：' + (error.message || '未知错误'));
  }
  init();
}


// 客户列表分页功能
const clientPagination = reactive({ current: 1, size: 10, total: 0 })
function handleClientPageChange(p) {
  clientPagination.current = p; init()
}
function handleClientSizeChange(s) {
  clientPagination.size = s; clientPagination.current = 1; init()
}



// 初始客户信息列表
// 引入全局注入的 axios 对象
const axios = inject('axios')
let arr = ref([])
const filters = reactive({
  clientId: '', // 客户ID
  clientType: '', // 客户类型
  clientName: '', // 客户姓名
  clientAge: '', // 客户年龄
  dateOfBirth: '', // 出生日期
  clientGender: '', // 客户性别
  clientCardNumber: '', // 身份证号
  bloodType: '', // 血型
  familyMember: '', // 家属
  clientPhone: '', // 电话号码
  careLevelName: '', // 护理级别ID
  careAdminId: '', // 护理管理员ID
  bedId: '', // 床位ID
  // careLevelName: ''// 护理级别名称
});
const init = async () => {
  let url = `client/searchByNameAndCareType`;
  const params = {
    clientName: filters.clientName,
    page: clientPagination.current, // 添加分页参数 current
    size: clientPagination.size     // 添加分页参数 size
  };
  try {
    const data = await axios.get(url, { params });
    arr.value = data.records
    clientPagination.total = data.total
    console.log('chongg', arr.value) // 打印查看数据
  } catch (error) {
    console.log(error)
    ElMessage.error(error.message || '获取数据失败')
    arr.value = []; // 确保在获取数据失败时，arr 为空数组
  }
}
// 调用初始化函数，在页面载入前把数据从后台拉取到前端
// 在对话框显示时请求护理级别数据
onMounted(() => {
  fetchCareLevels();
  init();
});


// 处理筛选信息，重新调用初始化客户信息列表
function handleFiltersChange() {
  init()
}

</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center; /* 将按钮居中对齐 */
  gap: 16px;  /* 按钮之间的间距 */
}
</style>